import type { PQResponse } from '@prequest/types'
import type { ActionFn } from '../interceptorActionHandler'

/**
 * 响应数据处理器
 * @param {object} response 响应上下文
 * @return {object}
 */
export const dataHandler: ActionFn = (response: PQResponse) => {
  const handler = () => {
    // error first形式
    const error = Number(response.data.code) === 200 ? null : response.data
    const data = Number(response.data.code) === 200 ? response.data.data : null
    if (response.statusCode === 200) {
      return Promise.resolve([error, data])
    } else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject([error, null])
    }
  }

  return { checkHandle: true, value: handler }
}
